﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using JapaneseLearning.Tools;

namespace JapaneseLearning
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private static readonly Dictionary<string, string> AllBaseKeyValue = new Dictionary<string, string>();

        private static string GetWord(string key)
        {
            return !AllBaseKeyValue.TryGetValue(key, out var word) ? string.Empty : word;
        }


        private readonly List<string> _randomList = new List<string>();
        private readonly Stack<string> _historyQueue = new Stack<string>();
        private readonly Stack<string> _oldNextQueue = new Stack<string>();

        private int _currentWordIndex = 0;
        private string _currentWordKey = string.Empty;

        public MainWindow()
        {
            Application.Current.MainWindow = this;
            InitializeComponent();
            this.Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            var baseWorkRes = new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/JapaneseLearning;component/Resources/BaseWorks.xaml")
            };
            foreach (DictionaryEntry item in baseWorkRes)
            {
                AllBaseKeyValue.Add(item.Key.ToString(), item.Value.ToString());
            }

            #region 默认加载所有

            var para = new List<string>
            {
                "aoyin",
                "banzhuo",
                "zhuo",
                "qing"
            };
            _randomList.AddRange(JapaneseTools.GetPingJiaKey(para.ToArray()));
            _randomList.AddRange(JapaneseTools.GetPianJiaKey(para.ToArray()));

            // 随机打乱
            _randomList.Shuffle();
            _random = new PrimeModRandom(_randomList.Count);
            this.WordTotalCountRun.Text = _randomList.Count.ToString();

            #endregion

            NextWordButtonBase_OnClick(null, null);
        }

        private byte _chooseInfo = 0x3F;
        private PrimeModRandom _random;

        private void LeftDrawer_OnClosed(object sender, RoutedEventArgs e)
        {
            var qingyin = QingYinButton.IsChecked ?? false;
            var zhuoyin = ZhuoYinButton.IsChecked ?? false;
            var banzhuoyin = BanZhuoYinButton.IsChecked ?? false;
            var aoyin = AoYinButton.IsChecked ?? false;
            var pingjia = PingJiaButton.IsChecked ?? false;
            var pianjia = PianJiaButton.IsChecked ?? false;

            if (!pingjia && !pianjia)
            {
                pingjia = true;
                PingJiaButton.IsChecked = true;
            }

            if (!qingyin && !zhuoyin && !banzhuoyin && !aoyin)
            {
                qingyin = true;
                QingYinButton.IsChecked = true;
            }

            var para = new List<string>();
            byte info = 0x00;
            if (pianjia) info |= 0x01;
            if (pingjia) info |= 0x02;
            if (aoyin)
            {
                info |= 0x04;
                para.Add("aoyin");
            }

            if (banzhuoyin)
            {
                info |= 0x08;
                para.Add("banzhuo");
            }

            if (zhuoyin)
            {
                info |= 0x10;
                para.Add("zhuo");
            }

            if (qingyin)
            {
                info |= 0x20;
                para.Add("qing");
            }

            if (info == _chooseInfo)
                return;
            _chooseInfo = info;
            _randomList.Clear();

            if (pingjia)
            {
                var keys = JapaneseTools.GetPingJiaKey(para.ToArray());
                _randomList.AddRange(keys);
            }

            if (pianjia)
            {
                var keys = JapaneseTools.GetPianJiaKey(para.ToArray());
                _randomList.AddRange(keys);
            }

            // 随机打乱
            _randomList.Shuffle();
            _random = new PrimeModRandom(_randomList.Count);
            ClearData();

            this.WordTotalCountRun.Text = _randomList.Count.ToString();
            NextWordButtonBase_OnClick(null, null);
        }

        private void NextWordButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(_currentWordKey))
                _historyQueue.Push(_currentWordKey);

            var key = _oldNextQueue.Any() ? _oldNextQueue.Pop() : _randomList[_random.Next()];
            var word = GetWord(key);
            if (string.IsNullOrEmpty(word))
                return;
            WordText.Text = word;
            WordTipsText.Text = key.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries)[2];
            _currentWordKey = key;

            if (_currentWordIndex++ >= _randomList.Count)
                _currentWordIndex = 1;
            LastWord.IsEnabled = _currentWordIndex > 0;
            this.WordIndexRun.Text = _currentWordIndex.ToString();
            WordTipsText.Visibility = Visibility.Hidden;
        }

        private void TipsButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            WordTipsText.Visibility = this.WordTipsText.IsVisible ? Visibility.Hidden : Visibility.Visible;
        }

        private void LastWord_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(_currentWordKey))
                _oldNextQueue.Push(_currentWordKey);

            var key = _historyQueue.Any() ? _historyQueue.Pop() : string.Empty;
            if (string.IsNullOrEmpty(key))
            {
                LastWord.IsEnabled = false;
                return;
            }

            var word = GetWord(key);
            if (string.IsNullOrEmpty(word))
                return;
            WordText.Text = word;
            WordTipsText.Text = key.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries)[2];
            _currentWordKey = key;

            LastWord.IsEnabled = --_currentWordIndex > 1;
            WordIndexRun.Text = _currentWordIndex.ToString();
            WordTipsText.Visibility = Visibility.Hidden;
        }

        private void ClearData()
        {
            _currentWordIndex = 0;
            _currentWordKey = string.Empty;
            _historyQueue.Clear();
            _oldNextQueue.Clear();
        }


        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (WordText == null)
                return;
            if (sender is ComboBox cbx)
            {
                var index = cbx.SelectedIndex;
                if (index == 0)
                {
                    WordText.FontFamily = new FontFamily("微软雅黑");
                    return;
                }

                var key = $"JapanFont{index}";
                if (!(Application.Current.FindResource(key) is FontFamily font))
                    return;
                WordText.FontFamily = font;
            }
        }


        #region 50音图

        private ShowImageWindow _window;

        private void ShowImageButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            _window?.Close();
            _window = new ShowImageWindow();
            _window.Closed += (s, b) => { _window = null; };
            _window.Show();
        }

        #endregion
    }
}